﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using VSSTQH.Properties;
using VSSTQH.DataAccess;
using VSSTQH.Reports;

namespace VSSTQH
{
    public partial class FrmEditPO : Form
    {
        #region Ctors

        /// <summary>
        /// Constructor for create new status
        /// </summary>
        public FrmEditPO()
        {
            InitializeComponent();
            Initialize();
        }

        #endregion

        #region Property Members

        #region Vehicle Scale Property
        private POModel _currentPO;
        /// <summary>
        /// Vehicle Scale Property
        /// </summary>
        public POModel CurrentPO
        {
            get { return _currentPO; }
            set
            {
                if (_currentPO != value)
                {
                    _currentPO = value;
                    LoadPO();
                }
            }
        }
        #endregion

        #endregion

        /// <summary>
        /// Initialize method
        /// </summary>
        private void Initialize()
        {
            #region Set value to some controls
            this.MaximizeBox = false;

            #endregion

            this.cboPoType.LostFocus += new EventHandler(cboPoType_LostFocus);
            this.btnSave.Click += new EventHandler(delegate
            {
                ClickButtonSave();
            });

            this.numFirstWeight.ValueChanged += new EventHandler(WeightValueChanged);
            this.numSecondWeight.ValueChanged += new EventHandler(WeightValueChanged);
            this.numFirstWeight.LostFocus += new EventHandler(numFirstWeight_LostFocus);
            this.numSecondWeight.LostFocus += new EventHandler(numSecondWeight_LostFocus);

            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
            this.btnPrint.Click += new EventHandler(delegate
            {
                try
                {
                    crTicket report = new crTicket();
                    report.SetDataSource(CollectionExtensions<POModel>.ConvertToDataTable(new List<POModel>() { CurrentPO }, "VSSTQH_POModel"));

                    SettingApp setting = new SettingApp();

                    if (Common.CheckPrinter(setting.ReceiptPrintName))
                        report.PrintOptions.PrinterName = setting.ReportPrintName;
                    report.PrintOptions.ApplyPageMargins(new CrystalDecisions.Shared.PageMargins(setting.MarginLeft, setting.MarginTop, setting.MarginRight, setting.MarginBottom));

                    if (setting.IsPreviewReportPrint)
                    {
                        FrmPrintPreview form = new FrmPrintPreview(report);
                        form.ShowDialog();
                    }
                    else
                    {
                        report.PrintToPrinter(1, false, 0, 0);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowAlert(ex.Message);
                }
            });

            // Set permission
            bool IsAdmin = (Common.UserLogin.GroupID == 1);
            //this.chkManual.Visible = IsAdmin;

            LoadData();

        }

        private void LoadData()
        {
            IProductDAO dao = new ProductDAO();
            IList<ProductModel> products = dao.GetAll();
            if (products != null)
            {
                this.cboProductID.DataSource = products;
                this.cboProductID.ValueMember = "ProductName";
                this.cboProductID.DisplayMember = "ProductID";

                this.cboProductID.Text = String.Empty;
            }

            IVendorDAO dao1 = new VendorDAO();
            IList<VendorModel> vendors = dao1.GetAll();
            if (vendors != null)
            {
                this.cboVendorID.DataSource = vendors;
                this.cboVendorID.ValueMember = "VendorName";
                this.cboVendorID.DisplayMember = "VendorID";

                this.cboVendorID.Text = String.Empty;
            }
        }

        void cboPoType_LostFocus(object sender, EventArgs e)
        {
            if (this.cboPoType.SelectedIndex > 0)
            {
                errorProvider.Clear();
                return;
            }
        }

        private void ClickButtonSave()
        {
            try
            {
                if (CurrentPO != null && ValidData())
                {
                    // Update Data
                    CurrentPO.VehicleID = txtVehicleID.Text;
                    CurrentPO.FirstWeight = (decimal)numFirstWeight.Value;
                    CurrentPO.SecondWeight = (decimal)numSecondWeight.Value;
                    DateTime temp;
                    if (DateTime.TryParse(mskScaleTime1.Text, out temp))
                        CurrentPO.FirstTime = temp;
                    if (DateTime.TryParse(mskScaleTime2.Text, out temp))
                        CurrentPO.SecondTime = temp;
                    CurrentPO.ActualWeight = (decimal)numWeight.Value;
                    CurrentPO.ActualWeight2 = (decimal)numActualWeight2.Value;
                    CurrentPO.Unit = txtUnit.Text;
                    CurrentPO.Unit2 = cboUnit2.Text;
                    CurrentPO.ProductID = txtProductID.Text;
                    CurrentPO.ProductName = txtProductName.Text;
                    CurrentPO.VendorID = txtVendorID.Text;
                    CurrentPO.VendorName = txtVendorName.Text;
                    CurrentPO.PoID = txtPOID.Text;
                    CurrentPO.Inbound = Convert.ToDecimal(numInbound.Value);
                    CurrentPO.InboundWeight = Convert.ToDecimal(numInboundWeight.Value);
                    CurrentPO.WBS = txtWBS.Text;
                    CurrentPO.Location = txtLocation.Text;
                    CurrentPO.PoType = cboPoType.SelectedIndex;

                    // Write to Database
                    IPODAO dao = new PODAO();
                    bool isNew = false;
                    if (dao.Save(CurrentPO, ref isNew))
                    {
                        if (CurrentPO.CreationDate.Date == DateTime.Today)
                        {

                            // Only write to file PO has secondweight > 0

                            decimal inbound = 0;
                            bool valid = Decimal.TryParse(this.numInbound.Text, out inbound);

                            if (valid)
                            {
                                string filename = String.Empty;
                                switch (this.cboPoType.SelectedIndex)
                                {
                                    case 1:
                                        filename = String.Format(Common.MM_C2S, inbound);
                                        break;
                                    case 2:
                                        filename = String.Format(Common.SD_C2S, inbound);
                                        break;
                                }

                                IList<POModel> completedPO = dao.GetBy(inbound, this.cboPoType.SelectedIndex, true);

                                if (completedPO != null && completedPO.Count > 0)
                                {
                                    if (!File.Exists(filename))
                                    {
                                        using (System.IO.FileStream fs = System.IO.File.Create(filename))
                                        {
                                            StreamWriter sw = new StreamWriter(fs);

                                            foreach (var item in completedPO)
                                            {
                                                sw.WriteLine(POMapper.ToCSV(item));
                                            }

                                            sw.Flush();
                                            fs.Close();
                                        }
                                    }
                                    else
                                    {
                                        using (System.IO.FileStream fs = File.OpenWrite(filename))
                                        {
                                            StreamWriter sw = new StreamWriter(fs);

                                            foreach (var item in completedPO)
                                            {
                                                sw.WriteLine(POMapper.ToCSV(item));
                                            }

                                            sw.Flush();
                                            fs.Close();
                                        }
                                    }
                                }

                                #region Process A line
                                //if (!File.Exists(filename))
                                //{
                                //    using (System.IO.FileStream fs = System.IO.File.Create(filename))
                                //    {
                                //        StreamWriter sw = new StreamWriter(fs);
                                //        sw.WriteLine(POMapper.ToCSV(CurrentPO));

                                //        sw.Flush();
                                //        fs.Close();
                                //    }
                                //}
                                //else
                                //{
                                //    //if (isNew)
                                //    //{
                                //    using (StreamWriter w = File.AppendText(filename))
                                //    {
                                //        w.WriteLine(POMapper.ToCSV(CurrentPO));
                                //        // Close the writer and underlying file.
                                //        w.Flush();
                                //        w.Close();
                                //    }


                                //    //}
                                //    //else
                                //    //{
                                //    //    string[] lines = File.ReadAllLines(filename);
                                //    //    string key = String.Format("{0},{1}", CurrentPO.Inbound, CurrentPO.SeqInbound);
                                //    //    int index = -1;
                                //    //    for (int i = 0; i < lines.Length; i++)
                                //    //    {
                                //    //        if (lines[i].StartsWith(key))
                                //    //        {
                                //    //            index = i;
                                //    //            break;
                                //    //        }
                                //    //    }
                                //    //    if (index > -1)
                                //    //    {
                                //    //        lines[index] = POMapper.ToCSV(CurrentPO);
                                //    //        File.WriteAllLines(filename, lines);
                                //    //    }
                                //    //    else
                                //    //    {
                                //    //        using (StreamWriter w = File.AppendText(filename))
                                //    //        {
                                //    //            w.WriteLine(POMapper.ToCSV(CurrentPO));
                                //    //            // Close the writer and underlying file.
                                //    //            w.Flush();
                                //    //            w.Close();
                                //    //        }

                                //    //        //FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
                                //    //        //StreamWriter sw = new StreamWriter(fs);

                                //    //        //sw.BaseStream.Seek(0, SeekOrigin.End);
                                //    //        //sw.WriteLine(POMapper.ToCSV(CurrentPO));

                                //    //        //sw.Flush();
                                //    //        //fs.Close();
                                //    //    }
                                //    //}
                                //}
                                #endregion
                            }
                        }

                        // End if Save

                        // Save successfully
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }

        bool ValidData()
        {
            if ((decimal)this.numFirstWeight.Value == 0)
            {
                Common.ShowAlert(Resources.NotInputFirstWeight);
                this.numFirstWeight.Focus();
                return false;
            }
            if (this.txtVehicleID.Text == String.Empty)
            {
                Common.ShowAlert(Resources.NotInputVehicle);
                this.txtVehicleID.Focus();
                return false;
            }
            if ((decimal)this.numSecondWeight.Value > 0)
            {
                if ((decimal)this.numFirstWeight.Value > (decimal)this.numSecondWeight.Value && cboPoType.SelectedIndex == 2)
                {
                    Common.ShowAlert(Resources.NotInput);
                    this.cboPoType.Focus();
                    return false;
                }
                if ((decimal)this.numFirstWeight.Value < (decimal)this.numSecondWeight.Value && cboPoType.SelectedIndex == 1)
                {
                    Common.ShowAlert(Resources.NotOutput);
                    this.cboPoType.Focus();
                    return false;
                }
            }

            return true;
        }

        #region Events
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
        }

        void numFirstWeight_LostFocus(object sender, EventArgs e)
        {
            if ((decimal)numFirstWeight.Value > 0)
            {
                this.mskScaleTime1.Text = String.Format("{0:d} {0:HH:mm}", DateTime.Now);
                this.numFirstWeight.Enabled = false;
            }
        }

        void numSecondWeight_LostFocus(object sender, EventArgs e)
        {
            if ((decimal)numSecondWeight.Value > 0)
            {
                this.mskScaleTime2.Text = String.Format("{0:d} {0:HH:mm}", DateTime.Now);
                this.numSecondWeight.Enabled = false;
            }
        }

        void WeightValueChanged(object sender, EventArgs e)
        {
            decimal firstWeight = (decimal)this.numFirstWeight.Value;
            decimal secondWeight = (decimal)this.numSecondWeight.Value;
            if (firstWeight > 0 && secondWeight > 0)
            {
                decimal compare = firstWeight - secondWeight;
                this.numWeight.Value = Math.Abs(compare);
            }
            else
            {
                this.numWeight.Value = 0;
            }
        }

        #endregion

        #region Methods
        /// <summary>
        /// Reset detail controls
        /// </summary>
        private void ResetDetails()
        {
            this.txtVehicleID.Text = String.Empty;
            this.numFirstWeight.Text = String.Empty;
            this.numSecondWeight.Text = String.Empty;
        }

        private void LoadPO()
        {
            if (CurrentPO != null)
            {
                //•	Số Inbound Delivery \ Outbound Delivery (*** Input ***)
                //•	STT trên Inbound trong SAP
                //•	Số PO
                //•	Mã Vendor
                //•	Tên Vendor
                //•	Mã hàng
                //•	Tên hàng
                //•	Kho
                //•	Số lượng inbound
                //•	Đơn vị tính
                //•	Tên hạng mục (WBS) 

                this.numInbound.Value = CurrentPO.Inbound;
                this.numSeq.Value = CurrentPO.SeqInbound;
                this.txtPOID.Text = CurrentPO.PoID;
                this.cboVendorID.Text = CurrentPO.VendorID;
                this.txtVendorID.Text = CurrentPO.VendorID;
                this.txtVendorName.Text = CurrentPO.VendorName;
                this.cboProductID.Text = CurrentPO.ProductID;
                this.txtProductID.Text = CurrentPO.ProductID;
                this.txtProductName.Text = CurrentPO.ProductName;
                this.txtLocation.Text = CurrentPO.Location;
                this.numInboundWeight.Value = CurrentPO.InboundWeight;
                this.txtUnit.Text = CurrentPO.Unit;
                this.cboUnit2.Text = CurrentPO.Unit2;
                this.txtWBS.Text = CurrentPO.WBS;
                this.txtVehicleID.Text = CurrentPO.VehicleID;
                this.numActualWeight2.Value = CurrentPO.ActualWeight2;

                this.numFirstWeight.Value = CurrentPO.FirstWeight;
                this.numSecondWeight.Value = CurrentPO.SecondWeight;
                this.mskScaleTime1.Text = String.Format("{0:d} {0:HH:mm}", CurrentPO.FirstTime);
                this.mskScaleTime2.Text = String.Format("{0:d} {0:HH:mm}", CurrentPO.SecondTime);
                if (CurrentPO.PoType.HasValue)
                    this.cboPoType.SelectedIndex = CurrentPO.PoType.Value;
            }
        }
        #endregion
    }
}